
package Server;
import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
/**
 * The client connection threrad
 * @author Samuel Millar
 */
class ClientConnection extends Thread implements Observer{

   private Socket client = null;
   private ObjectOutputStream oos = null;
   private ObjectInputStream ois = null;
   private DatabaseInterface daoInterface = new DatabaseInterface();
   private ArrayList<String> request = new ArrayList<String>();
   private ArrayList<String> reply = new ArrayList<String>();
   public ClientConnection() {}
   public ClientConnection(Socket clientSocket) throws IOException {
        client = clientSocket;
        client.setSoTimeout(10000);
        daoInterface.addObserver( this );
        try {
            oos = new ObjectOutputStream(client.getOutputStream());
            ois = new ObjectInputStream(client.getInputStream());
        } catch(Exception ex) {
            try {
                client.close();
            }catch (Exception e) {
                System.out.println(e.getMessage());
            }
            return;
        }
        this.run();
    }
   /**
     * Runs the client connection, reads in the client request and outputs the reply.
     */
    public void run() {
       try {
           while((request = (ArrayList<String>)ois.readObject()) != null){
               reply = daoInterface.receiveRequest(request);
               oos.writeObject(reply);
           }
       }catch(Exception e) {
           System.out.println(e.getMessage());
       }
       try {
           oos.close();
           ois.close();
           client.close();
       }catch(Exception e) {
           System.out.println(e.getMessage());
       }
    }
   /**
     * Receives an update from the oberservable
     */
    public void update (Observable obj, Object arg)
    {
        if (arg instanceof String)
        {
            String resp;
            resp = (String) arg;
            System.out.println("\nReceived Response: "+ resp );
        }
    }
}